package com.punai.evaluationSystem.costDataEvalute.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.punai.common.constant.HttpStatus;
import com.punai.common.core.page.PageDomain;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.core.page.TableSupport;
import com.punai.common.utils.PageUtils;
import com.punai.common.utils.StringUtil;
import com.punai.dataclean.constants.CostDataConstanta;
import com.punai.evaluationSystem.costDataEvalute.bo.CostDataEvaluteBo;
import com.punai.evaluationSystem.costDataEvalute.bo.EvaluationDataPriceBo;
import com.punai.evaluationSystem.costDataEvalute.domain.EvaluationCbInfo;
import com.punai.evaluationSystem.costDataEvalute.domain.EvaluationDataPrice;
import com.punai.evaluationSystem.costDataEvalute.domain.EvaluationResults;
import com.punai.evaluationSystem.costDataEvalute.mapper.EvaluationCbInfoMapper;
import com.punai.evaluationSystem.costDataEvalute.mapper.EvaluationDataPriceMapper;
import com.punai.evaluationSystem.costDataEvalute.mapper.EvaluationResultsMapper;
import com.punai.evaluationSystem.costDataEvalute.service.FeeItemPriceEvaluteService;
import com.punai.externalccb.domain.EcoCbfeeitem;
import com.punai.standard.domain.*;
import com.punai.standard.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class FeeItemPriceEvaluteServiceImpl implements FeeItemPriceEvaluteService {
    @Autowired
    private EvaluationResultsMapper evaluationResultsMapper;
    @Autowired
    private EvaluationCbInfoMapper evaluationCbInfoMapper;
    @Autowired
    private EvaluationDataPriceMapper evaluationDataPriceMapper;
    @Autowired
    private StaGxChapterMapper staGxChapterMapper;
    @Autowired
    private StaGxFeeMapper staGxFeeMapper;
    @Autowired
    private StaFbChapterMapper staFbChapterMapper;
    @Autowired
    private StaClChapterMapper staClChapterMapper;
    @Autowired
    private StaJxChapterMapper staJxChapterMapper;
    @Autowired
    private StaFbFeeMapper staFbFeeMapper;
    @Autowired
    private StaClFeeMapper staClFeeMapper;
    @Autowired
    private StaJxFeeMapper staJxFeeMapper;
    @Autowired
    private StaVersionMapper staVersionMapper;

    private static final String GX_ROOT_ID = "GX_ROOT_ID";
    private static final String CB_ROOT_ID = "CB_ROOT_ID";

    @Override
    public List<EvaluationResults> initResultsSrTable(CostDataEvaluteBo costDataEvaluteBo) {
        CostDataEvaluteBo convert = CostDataEvaluteBo.convert(costDataEvaluteBo);
        PageHelper.startPage(convert.getPageNum(),convert.getPageSize());
        List<EvaluationResults> resultsList = evaluationResultsMapper.selectEvaluationResults(new CostDataEvaluteBo() {{
            setEngineeringMajor(convert.getEngineeringMajor());
            setClassification(convert.getEvaluteType());
            setEvaluteType("01");
            setProjectDept(convert.getProjectDept());
            setAddress(convert.getAddress());
            setPriceType(convert.getPriceType());
            if (CollUtil.isNotEmpty(convert.getDateRange())){
                setTimeStart(convert.getDateRange().get(0));
                setTimeEnd(convert.getDateRange().get(1));
            }
        }});
        return resultsList;
    }

    @Override
    public int saveAssetLibrary(List<String> resultIds) {
        return evaluationResultsMapper.updateResultsSrByIdIn(resultIds, "1");
    }

    @Override
    public List<CostDataEvaluteBo> initCleanDataTable(CostDataEvaluteBo dataEvaluteBo) {
        CostDataEvaluteBo convert = CostDataEvaluteBo.convert(dataEvaluteBo);
        String versionId = convert.getVersionId();
        String chapterId = convert.getCategoryId();
        String gxCbType = convert.getGxCbType();//工序 or 成本
        String type = convert.getType();
        Map<String, String> codesMap = new HashMap<>();
        if (CostDataConstanta.Tabs.FB_0.getCode().equals(type)) {
            if (StrUtil.equals(GX_ROOT_ID, gxCbType)){
                List<String> chapterIds = new ArrayList<>();
                if (StrUtil.isNotEmpty(chapterId)) {
                    chapterIds.add(chapterId);
                    List<StaGxChapter> childByPid = staGxChapterMapper.selectList(Wrappers.<StaGxChapter>lambdaQuery()
                            .eq(StaGxChapter::getVersionId,versionId)
                            .apply(StrUtil.isNotEmpty(chapterId),"find_in_set('"+chapterId+"',pids)"));
                    if (CollUtil.isNotEmpty(childByPid)) {
                        chapterIds.addAll(childByPid.stream().map(StaGxChapter::getId).collect(Collectors.toList()));
                    }
                }
                List<StaGxFee> staGxFees = staGxFeeMapper.selectList(
                        Wrappers.<StaGxFee>lambdaQuery()
                                .in(chapterIds.size() > 0, StaGxFee::getChapterId, chapterIds)
                                .eq(StaGxFee::getVersionId, versionId)
                                .orderBy(true, true, StaGxFee::getCode)
                                .orderBy(true, true, StaGxFee::getOrderNum)
                );
                //获取所有费用项编码
                for (StaGxFee staGxFee : staGxFees) {
                    codesMap.put(staGxFee.getCode(), staGxFee.getContent() + "@null" + staGxFee.getCalcRule());
                }
            } else if (StrUtil.equals(CB_ROOT_ID, gxCbType)){
                List<String> chapterIds = new ArrayList<>();
                if (StrUtil.isNotEmpty(chapterId)) {
                    chapterIds.add(chapterId);
                    List<StaFbChapter> childByPid = staFbChapterMapper.selectList(Wrappers.<StaFbChapter>lambdaQuery()
                            .eq(StaFbChapter::getVersionId, versionId)
                            .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                    if (CollUtil.isNotEmpty(childByPid)) {
                        chapterIds.addAll(childByPid.stream().map(StaFbChapter::getId).collect(Collectors.toList()));
                    }
                }
                List<StaFbFee> staFbFees = staFbFeeMapper.selectList(
                        Wrappers.<StaFbFee>lambdaQuery()
                                .in(chapterIds.size() > 0, StaFbFee::getChapterId, chapterIds)
                                .eq(StaFbFee::getVersionId, versionId)
                                .orderBy(true, true, StaFbFee::getCode)
                                .orderBy(true, true, StaFbFee::getOrderNum)
                );
                //获取所有费用项编码
                for (StaFbFee staFbFee : staFbFees) {
                    codesMap.put(staFbFee.getCode(), staFbFee.getContent() + "@null" + staFbFee.getCalcRule());
                }
            }
        } else if (CostDataConstanta.Tabs.CL_1.getCode().equals(type)) {
            List<String> chapterIds = new ArrayList<>();
            if (StrUtil.isNotEmpty(chapterId)) {
                chapterIds.add(chapterId);
                List<StaClChapter> childByPid = staClChapterMapper.selectList(Wrappers.<StaClChapter>lambdaQuery()
                        .eq(StaClChapter::getVersionId, versionId)
                        .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                if (CollUtil.isNotEmpty(chapterIds)) {
                    chapterIds.addAll(childByPid.stream().map(StaClChapter::getId).collect(Collectors.toList()));
                }
            }
            List<StaClFee> staFbFees = staClFeeMapper.selectList(
                    Wrappers.<StaClFee>lambdaQuery()
                            .in(chapterIds.size() > 0, StaClFee::getChapterId, chapterIds)
                            .eq(StaClFee::getVersionId, versionId)
                            .orderBy(true, true, StaClFee::getCode)
                            .orderBy(true, true, StaClFee::getOrderNum)
            );
            //获取所有费用项编码
            for (StaClFee staclFee : staFbFees) {
                codesMap.put(staclFee.getCode(), "1" + "@null" + "1");
            }
        } else if (CostDataConstanta.Tabs.JX_2.getCode().equals(type)) {
            List<String> chapterIds = new ArrayList<>();
            if (StrUtil.isNotEmpty(chapterId)) {
                chapterIds.add(chapterId);
                List<StaJxChapter> childByPid = staJxChapterMapper.selectList(Wrappers.<StaJxChapter>lambdaQuery()
                        .eq(StaJxChapter::getVersionId, versionId)
                        .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                if (CollUtil.isNotEmpty(chapterIds)) {
                    chapterIds.addAll(childByPid.stream().map(StaJxChapter::getId).collect(Collectors.toList()));
                }
            }
            List<StaJxFee> staFbFees = staJxFeeMapper.selectList(
                    Wrappers.<StaJxFee>lambdaQuery()
                            .in(chapterIds.size() > 0, StaJxFee::getChapterId, chapterIds)
                            .eq(StaJxFee::getVersionId, versionId)
                            .orderBy(true, true, StaJxFee::getCode)
                            .orderBy(true, true, StaJxFee::getOrderNum)
            );
            //获取所有费用项编码
            for (StaJxFee stajxFee : staFbFees) {
                codesMap.put(stajxFee.getCode(), "1" + "@null" + "1");
            }
        } else if (CostDataConstanta.Tabs.JJ_3.getCode().equals(type)) {

        }
        if (codesMap.keySet().size() == 0) return Collections.emptyList();
        convert.setCodes(new ArrayList<>(codesMap.keySet()));
        if (StringUtil.isNotNullOrEmpty(convert.getIsIncludeStr()) ){
            if (convert.getIsIncludeStr().equals("true")){
                convert.setInclude("10086");
            }else {
                convert.setNotInclude("10086");
            }
        }
        List<CostDataEvaluteBo> costDataEvaluteBos = evaluationResultsMapper.selectCleanData(convert);
        return costDataEvaluteBos;
    }

    @Override
    public TableDataInfo initCleanDataEvaluteTable(CostDataEvaluteBo costDataEvaluteBo) {
        CostDataEvaluteBo convert = CostDataEvaluteBo.convert(costDataEvaluteBo);
        List<EvaluationDataPriceBo> res = new ArrayList<>();

        String versionId = convert.getVersionId();
        String chapterId = convert.getCategoryId();
        String gxCbType = convert.getGxCbType();//工序 or 成本
        String type = convert.getType();
        List<String> idList = Arrays.asList(convert.getIdStr().split(",", -1));
        Map<String, String> codesMap = new HashMap<>();
        if (CostDataConstanta.Tabs.FB_0.getCode().equals(type)) {
            if (StrUtil.equals(GX_ROOT_ID, gxCbType)){
                List<String> chapterIds = new ArrayList<>();
                if (StrUtil.isNotEmpty(chapterId)) {
                    chapterIds.add(chapterId);
                    List<StaGxChapter> childByPid = staGxChapterMapper.selectList(Wrappers.<StaGxChapter>lambdaQuery()
                            .eq(StaGxChapter::getVersionId,versionId)
                            .apply(StrUtil.isNotEmpty(chapterId),"find_in_set('"+chapterId+"',pids)"));
                    if (CollUtil.isNotEmpty(childByPid)) {
                        chapterIds.addAll(childByPid.stream().map(StaGxChapter::getId).collect(Collectors.toList()));
                    }
                }
                List<StaGxFee> staGxFees = staGxFeeMapper.selectList(
                        Wrappers.<StaGxFee>lambdaQuery()
                                .in(chapterIds.size() > 0, StaGxFee::getChapterId, chapterIds)
                                .eq(StaGxFee::getVersionId, versionId)
                                .orderBy(true, true, StaGxFee::getCode)
                                .orderBy(true, true, StaGxFee::getOrderNum)
                );
                //获取所有费用项编码
                for (StaGxFee staGxFee : staGxFees) {
                    codesMap.put(staGxFee.getCode(), staGxFee.getContent() + "@null" + staGxFee.getCalcRule());
                }
            } else if (StrUtil.equals(CB_ROOT_ID, gxCbType)){
                List<String> chapterIds = new ArrayList<>();
                if (StrUtil.isNotEmpty(chapterId)) {
                    chapterIds.add(chapterId);
                    List<StaFbChapter> childByPid = staFbChapterMapper.selectList(Wrappers.<StaFbChapter>lambdaQuery()
                            .eq(StaFbChapter::getVersionId, versionId)
                            .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                    if (CollUtil.isNotEmpty(childByPid)) {
                        chapterIds.addAll(childByPid.stream().map(StaFbChapter::getId).collect(Collectors.toList()));
                    }
                }
                List<StaFbFee> staFbFees = staFbFeeMapper.selectList(
                        Wrappers.<StaFbFee>lambdaQuery()
                                .in(chapterIds.size() > 0, StaFbFee::getChapterId, chapterIds)
                                .eq(StaFbFee::getVersionId, versionId)
                                .orderBy(true, true, StaFbFee::getCode)
                                .orderBy(true, true, StaFbFee::getOrderNum)
                );
                //获取所有费用项编码
                for (StaFbFee staFbFee : staFbFees) {
                    codesMap.put(staFbFee.getCode(), staFbFee.getContent() + "@null" + staFbFee.getCalcRule());
                }
            }
        } else if (CostDataConstanta.Tabs.CL_1.getCode().equals(type)) {
            List<String> chapterIds = new ArrayList<>();
            if (StrUtil.isNotEmpty(chapterId)) {
                chapterIds.add(chapterId);
                List<StaClChapter> childByPid = staClChapterMapper.selectList(Wrappers.<StaClChapter>lambdaQuery()
                        .eq(StaClChapter::getVersionId, versionId)
                        .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                if (CollUtil.isNotEmpty(chapterIds)) {
                    chapterIds.addAll(childByPid.stream().map(StaClChapter::getId).collect(Collectors.toList()));
                }
            }
            List<StaClFee> staFbFees = staClFeeMapper.selectList(
                    Wrappers.<StaClFee>lambdaQuery()
                            .in(chapterIds.size() > 0, StaClFee::getChapterId, chapterIds)
                            .eq(StaClFee::getVersionId, versionId)
                            .orderBy(true, true, StaClFee::getCode)
                            .orderBy(true, true, StaClFee::getOrderNum)
            );
            //获取所有费用项编码
            for (StaClFee staclFee : staFbFees) {
                codesMap.put(staclFee.getCode(), "1" + "@null" + "1");
            }
        } else if (CostDataConstanta.Tabs.JX_2.getCode().equals(type)) {
            List<String> chapterIds = new ArrayList<>();
            if (StrUtil.isNotEmpty(chapterId)) {
                chapterIds.add(chapterId);
                List<StaJxChapter> childByPid = staJxChapterMapper.selectList(Wrappers.<StaJxChapter>lambdaQuery()
                        .eq(StaJxChapter::getVersionId, versionId)
                        .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                if (CollUtil.isNotEmpty(chapterIds)) {
                    chapterIds.addAll(childByPid.stream().map(StaJxChapter::getId).collect(Collectors.toList()));
                }
            }
            List<StaJxFee> staFbFees = staJxFeeMapper.selectList(
                    Wrappers.<StaJxFee>lambdaQuery()
                            .in(chapterIds.size() > 0, StaJxFee::getChapterId, chapterIds)
                            .eq(StaJxFee::getVersionId, versionId)
                            .orderBy(true, true, StaJxFee::getCode)
                            .orderBy(true, true, StaJxFee::getOrderNum)
            );
            //获取所有费用项编码
            for (StaJxFee stajxFee : staFbFees) {
                codesMap.put(stajxFee.getCode(), "1" + "@null" + "1");
            }
        } else if (CostDataConstanta.Tabs.JJ_3.getCode().equals(type)) {

        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(res);
        rspData.setTotal(res.size());
        if (codesMap.keySet().size() == 0) return rspData;
        convert.setCodes(new ArrayList<>(codesMap.keySet()));
        if (CollUtil.isNotEmpty(idList)){
            for (String id : idList) {
                List<String> idAndAddress = Arrays.asList(id.split("=", -1));
                if (CollUtil.isEmpty(idAndAddress)) continue;
                convert.setId(idAndAddress.get(0));
                convert.setAddress(idAndAddress.get(1));
                convert.setPageSize(null);
                List<CostDataEvaluteBo> boList = evaluationResultsMapper.selectCleanDataEvaluteList(convert);
                if (CollUtil.isNotEmpty(boList)){
                    EvaluationDataPriceBo bo = new EvaluationDataPriceBo();
                    bo.setId(boList.get(0).getId());
                    bo.setCode(boList.get(0).getFyxCode());
                    bo.setName(boList.get(0).getFyxName());;
                    bo.setTzz(boList.get(0).getTzz());
                    bo.setRegion(boList.get(0).getAddress());
                    bo.setJldw(boList.get(0).getJldw());
                    bo.setJgsl(boList.size());
                    bo.setGznr(boList.get(0).getGznr());
                    bo.setJsgz(boList.get(0).getJsgz());
                    bo.setYycs(boList.get(0).getYycs());
                    List<BigDecimal> priceList = boList.stream().filter(v -> v.getPrice() != null).map(CostDataEvaluteBo::getPrice).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(priceList)){
                        BigDecimal avgValue = priceList.stream().reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(boList.size()), 3, BigDecimal.ROUND_HALF_UP);
                        BigDecimal max = priceList.stream().max(Comparator.comparing(x -> x)).orElse(null).setScale(3,BigDecimal.ROUND_HALF_UP);
                        BigDecimal min = priceList.stream().min(Comparator.comparing(x -> x)).orElse(null).setScale(3,BigDecimal.ROUND_HALF_UP);
                        bo.setPriceRange(min +"-" +max);
                        BigDecimal modalNums = getModalNums(priceList);
                        BigDecimal jqAvg = getJqAvg2(id,null,convert);
                        BigDecimal median = getMedian(priceList);
                        BigDecimal qdqxAvg = getQdqxAvg(priceList);
                        bo.setNumber(modalNums);//众数
                        bo.setSsavg(avgValue);//算数平均值
                        bo.setAvg(jqAvg);//加权平均值
                        bo.setMedian(median);//中位数
                        bo.setQdqxAvg(qdqxAvg);//去大去小平均值
                        //0：最大值 1：最小值 2：正常值
                        Map<BigDecimal,String> colorMap = new HashMap<BigDecimal,String>(){{
                            put(modalNums,"2");
                            put(avgValue,"2");
                            put(jqAvg,"2");
                            put(median,"2");
                            put(qdqxAvg,"2");
                        }};
                        List<BigDecimal> sortValue = colorMap.keySet().stream().filter(v->v!=null).sorted().collect(Collectors.toList());//进行排序
                        if (CollUtil.isNotEmpty(sortValue)){
                            BigDecimal minValue = sortValue.get(0);
                            BigDecimal maxValue = sortValue.get(sortValue.size() - 1);
                            colorMap.put(minValue,"0");
                            colorMap.put(maxValue,"1");
                        }
                        bo.setNumberColor(colorMap.get(modalNums));
                        bo.setSsavgColor(colorMap.get(avgValue));
                        bo.setAvgColor(colorMap.get(jqAvg));
                        bo.setMedianColor(colorMap.get(median));
                        bo.setQdqxAvgColor(colorMap.get(qdqxAvg));
                    }
                    res.add(bo);
                }
            }
        }


        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageSize = pageDomain.getPageSize();
        int start = (pageDomain.getPageNum()-1) * pageSize;
        int end = start + pageSize;
        if (end>res.size()) end = res.size();
        List<EvaluationDataPriceBo> list = res.subList(start, end);

        rspData.setRows(list);
        rspData.setTotal(res.size());
        return rspData;
    }

    @Override
    public EvaluationDataPriceBo recalculationPrice(CostDataEvaluteBo dataEvaluteBo) {
        CostDataEvaluteBo convert = CostDataEvaluteBo.convert(dataEvaluteBo);
        EvaluationDataPriceBo res = new EvaluationDataPriceBo();
        List<String> singleFeeId = Arrays.asList(convert.getSingleFeeId().split("=", -1));
        List<String> ids = Arrays.asList(convert.getIdStr().split(",", -1));
        if (CollUtil.isNotEmpty(singleFeeId)){
            String id = singleFeeId.get(0);
            String address = singleFeeId.get(1);
            res.setId(id);
            res.setRegion(address);
            convert.setId(id);
            convert.setAddress(address);
            convert.setOids(ids);
            List<CostDataEvaluteBo> boList = null;
            if (StringUtil.isNotNullOrEmpty(convert.getViewOrEdit()) && convert.getViewOrEdit().equals("view")){
                boList = evaluationCbInfoMapper.initTableDetailInfoData(convert);
            }else {
                boList = evaluationResultsMapper.selectCleanDataEvaluteList(convert);
            }
            if (CollUtil.isNotEmpty(boList)){
                res.setCode(boList.get(0).getFyxCode());
                res.setName(boList.get(0).getFyxName());;
                res.setTzz(boList.get(0).getTzz());
                res.setJldw(boList.get(0).getJldw());
                res.setJgsl(boList.size());
                res.setGznr(boList.get(0).getGznr());
                res.setJsgz(boList.get(0).getJsgz());
                res.setYycs(boList.get(0).getYycs());
                List<BigDecimal> priceList = boList.stream().filter(v -> v.getPrice() != null).map(CostDataEvaluteBo::getPrice).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(priceList)){
                    BigDecimal avgValue = priceList.stream().reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(boList.size()), 3, BigDecimal.ROUND_HALF_UP);
                    BigDecimal max = priceList.stream().max(Comparator.comparing(x -> x)).orElse(null).setScale(3,BigDecimal.ROUND_HALF_UP);
                    BigDecimal min = priceList.stream().min(Comparator.comparing(x -> x)).orElse(null).setScale(3,BigDecimal.ROUND_HALF_UP);
                    res.setPriceRange(min +"-" +max);
                    BigDecimal modalNums = getModalNums(priceList);
                    BigDecimal jqAvg = getJqAvg(boList,convert.getJqAvg());
                    BigDecimal median = getMedian(priceList);
                    BigDecimal qdqxAvg = getQdqxAvg(priceList);
                    res.setNumber(modalNums);//众数
                    res.setSsavg(avgValue);//算数平均值
                    res.setAvg(jqAvg);//加权平均值
                    res.setMedian(median);//中位数
                    res.setQdqxAvg(qdqxAvg);//去大去小平均值
                    //0：最小值 1：最大值 2：正常值
                    Map<BigDecimal,String> colorMap = new HashMap<BigDecimal,String>(){{
                        put(modalNums,"2");
                        put(avgValue,"2");
                        put(jqAvg,"2");
                        put(median,"2");
                        put(qdqxAvg,"2");
                    }};
                    List<BigDecimal> sortValue = colorMap.keySet().stream().filter(v->v!=null).sorted().collect(Collectors.toList());//进行排序
                    if (CollUtil.isNotEmpty(sortValue)){
                        BigDecimal minValue = sortValue.get(0);
                        BigDecimal maxValue = sortValue.get(sortValue.size() - 1);
                        colorMap.put(minValue,"0");
                        colorMap.put(maxValue,"1");
                    }
                    res.setNumberColor(colorMap.get(modalNums));
                    res.setSsavgColor(colorMap.get(avgValue));
                    res.setAvgColor(colorMap.get(jqAvg));
                    res.setMedianColor(colorMap.get(median));
                    res.setQdqxAvgColor(colorMap.get(qdqxAvg));
                }
            }
        }
        return res;
    }

    @Override
    public int saveEvaluationPrice(CostDataEvaluteBo evaluteBo) {
        int insert;
        CostDataEvaluteBo costDataEvaluteBo = CostDataEvaluteBo.convert(evaluteBo);
        String titleName = costDataEvaluteBo.getName();
        List<EvaluationDataPrice> priceSaveData = costDataEvaluteBo.getPriceSaveData();
        List<String> ids = costDataEvaluteBo.getIds();//明细id
        Map<BigDecimal, List<EvaluationDataPrice>> btjgsl = priceSaveData.stream().filter(v -> v.getUserPrice() != null).collect(Collectors.groupingBy(EvaluationDataPrice::getUserPrice, Collectors.toList()));
        //保存结果表
        EvaluationResults results = new EvaluationResults();
        results.setIsassets(0);//不存在资产库
        results.setEvaluateType("01");
        results.setClassification(costDataEvaluteBo.getType());
        results.setPjjgsj(titleName);
        results.setCount(priceSaveData.size());
        results.setBtjgsl(btjgsl.size());
        results.setPriceType(costDataEvaluteBo.getEngineeringMajor());//属于哪一种“工程专业”
        insert = evaluationResultsMapper.insert(results);
        //保存数据明细表
        if (CollUtil.isNotEmpty(priceSaveData)){
            for (EvaluationDataPrice priceSaveDatum : priceSaveData) {
                priceSaveDatum.setAvgType(costDataEvaluteBo.getJqAvg());
                priceSaveDatum.setClassification(costDataEvaluteBo.getType());
                priceSaveDatum.setOid(priceSaveDatum.getId());
                priceSaveDatum.setPid(results.getId());
                priceSaveDatum.setId(null);
                insert = evaluationDataPriceMapper.insert(priceSaveDatum);
                if (CollUtil.isNotEmpty(ids)){
                    List<CostDataEvaluteBo> boList = evaluationResultsMapper.selectCleanDataEvaluteList(new CostDataEvaluteBo() {{
                        setAddress(priceSaveDatum.getRegion());
                        setId(priceSaveDatum.getOid());
                        setOids(ids);
                    }});
                    List<EvaluationCbInfo> convertCbInfo = EvaluationCbInfo.convert(priceSaveDatum.getId(), boList);
                    if (CollUtil.isNotEmpty(convertCbInfo)){
                        for (EvaluationCbInfo info : convertCbInfo) {
                            insert = evaluationCbInfoMapper.insert(info);
                        }
                    }
                }
            }
        }
        return insert;
    }

    @Override
    public List<String> cleanDataInfoIdList(CostDataEvaluteBo bo) {
        CostDataEvaluteBo costDataEvaluteBo = CostDataEvaluteBo.convert(bo);
        List<String> res = new ArrayList<>();
        List<String> idAndAddressList = Arrays.asList(costDataEvaluteBo.getIdStr().split(",", -1));
        for (String id : idAndAddressList) {
            List<String> idAndAddress = Arrays.asList(id.split("=", -1));
            costDataEvaluteBo.setId(idAndAddress.get(0));
            costDataEvaluteBo.setAddress(idAndAddress.get(1));
            costDataEvaluteBo.setPageSize(null);
            List<CostDataEvaluteBo> boList = evaluationResultsMapper.initTableDetailInfoData(costDataEvaluteBo);
            res.addAll(boList.stream().map(CostDataEvaluteBo::getId).collect(Collectors.toList()));
        }
        return res;
    }

    @Override
    public List<CostDataEvaluteBo> initTableDetailInfoData(CostDataEvaluteBo dataEvaluteBo) {
        CostDataEvaluteBo costDataEvaluteBo = CostDataEvaluteBo.convert(dataEvaluteBo);
        List<CostDataEvaluteBo> res = null;
        List<String> idAndAddress = Arrays.asList(costDataEvaluteBo.getIdStr().split("=", -1));
        if (CollUtil.isNotEmpty(idAndAddress)){
            costDataEvaluteBo.setId(idAndAddress.get(0));
            costDataEvaluteBo.setAddress(idAndAddress.get(1));
        }
        if (StringUtil.isNotNullOrEmpty(costDataEvaluteBo.getViewOrEdit()) && costDataEvaluteBo.getViewOrEdit().equals("view")){
            res = evaluationCbInfoMapper.initTableDetailInfoData(new CostDataEvaluteBo(){{
                setId(costDataEvaluteBo.getId());
                setAddress(costDataEvaluteBo.getAddress());
            }});
        }else {
            res = evaluationResultsMapper.initTableDetailInfoData(costDataEvaluteBo);
        }
        return res;
    }

    @Override
    public List<EvaluationDataPriceBo> initEvaluteDataList(CostDataEvaluteBo costDataEvaluteBo) {
        List<EvaluationDataPriceBo> res = new ArrayList<>();
        String versionId = costDataEvaluteBo.getVersionId();
        String chapterId = costDataEvaluteBo.getCategoryId();
        String gxCbType = costDataEvaluteBo.getGxCbType();//工序 or 成本
        String type = costDataEvaluteBo.getType();
        Map<String, String> codesMap = new HashMap<>();
        if (CostDataConstanta.Tabs.FB_0.getCode().equals(type)) {
            if (StrUtil.equals(GX_ROOT_ID, gxCbType)){
                List<String> chapterIds = new ArrayList<>();
                if (StrUtil.isNotEmpty(chapterId)) {
                    chapterIds.add(chapterId);
                    List<StaGxChapter> childByPid = staGxChapterMapper.selectList(Wrappers.<StaGxChapter>lambdaQuery()
                            .eq(StaGxChapter::getVersionId,versionId)
                            .apply(StrUtil.isNotEmpty(chapterId),"find_in_set('"+chapterId+"',pids)"));
                    if (CollUtil.isNotEmpty(childByPid)) {
                        chapterIds.addAll(childByPid.stream().map(StaGxChapter::getId).collect(Collectors.toList()));
                    }
                }
                List<StaGxFee> staGxFees = staGxFeeMapper.selectList(
                        Wrappers.<StaGxFee>lambdaQuery()
                                .in(chapterIds.size() > 0, StaGxFee::getChapterId, chapterIds)
                                .eq(StaGxFee::getVersionId, versionId)
                                .orderBy(true, true, StaGxFee::getCode)
                                .orderBy(true, true, StaGxFee::getOrderNum)
                );
                //获取所有费用项编码
                for (StaGxFee staGxFee : staGxFees) {
                    codesMap.put(staGxFee.getCode(), staGxFee.getContent() + "@null" + staGxFee.getCalcRule());
                }
            } else if (StrUtil.equals(CB_ROOT_ID, gxCbType)){
                List<String> chapterIds = new ArrayList<>();
                if (StrUtil.isNotEmpty(chapterId)) {
                    chapterIds.add(chapterId);
                    List<StaFbChapter> childByPid = staFbChapterMapper.selectList(Wrappers.<StaFbChapter>lambdaQuery()
                            .eq(StaFbChapter::getVersionId, versionId)
                            .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                    if (CollUtil.isNotEmpty(childByPid)) {
                        chapterIds.addAll(childByPid.stream().map(StaFbChapter::getId).collect(Collectors.toList()));
                    }
                }
                List<StaFbFee> staFbFees = staFbFeeMapper.selectList(
                        Wrappers.<StaFbFee>lambdaQuery()
                                .in(chapterIds.size() > 0, StaFbFee::getChapterId, chapterIds)
                                .eq(StaFbFee::getVersionId, versionId)
                                .orderBy(true, true, StaFbFee::getCode)
                                .orderBy(true, true, StaFbFee::getOrderNum)
                );
                //获取所有费用项编码
                for (StaFbFee staFbFee : staFbFees) {
                    codesMap.put(staFbFee.getCode(), staFbFee.getContent() + "@null" + staFbFee.getCalcRule());
                }
            }
        } else if (CostDataConstanta.Tabs.CL_1.getCode().equals(type)) {
            List<String> chapterIds = new ArrayList<>();
            if (StrUtil.isNotEmpty(chapterId)) {
                chapterIds.add(chapterId);
                List<StaClChapter> childByPid = staClChapterMapper.selectList(Wrappers.<StaClChapter>lambdaQuery()
                        .eq(StaClChapter::getVersionId, versionId)
                        .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                if (CollUtil.isNotEmpty(chapterIds)) {
                    chapterIds.addAll(childByPid.stream().map(StaClChapter::getId).collect(Collectors.toList()));
                }
            }
            List<StaClFee> staFbFees = staClFeeMapper.selectList(
                    Wrappers.<StaClFee>lambdaQuery()
                            .in(chapterIds.size() > 0, StaClFee::getChapterId, chapterIds)
                            .eq(StaClFee::getVersionId, versionId)
                            .orderBy(true, true, StaClFee::getCode)
                            .orderBy(true, true, StaClFee::getOrderNum)
            );
            //获取所有费用项编码
            for (StaClFee staclFee : staFbFees) {
                codesMap.put(staclFee.getCode(), "1" + "@null" + "1");
            }
        } else if (CostDataConstanta.Tabs.JX_2.getCode().equals(type)) {
            List<String> chapterIds = new ArrayList<>();
            if (StrUtil.isNotEmpty(chapterId)) {
                chapterIds.add(chapterId);
                List<StaJxChapter> childByPid = staJxChapterMapper.selectList(Wrappers.<StaJxChapter>lambdaQuery()
                        .eq(StaJxChapter::getVersionId, versionId)
                        .apply(StrUtil.isNotEmpty(chapterId), "find_in_set('" + chapterId + "',pids)"));
                if (CollUtil.isNotEmpty(chapterIds)) {
                    chapterIds.addAll(childByPid.stream().map(StaJxChapter::getId).collect(Collectors.toList()));
                }
            }
            List<StaJxFee> staFbFees = staJxFeeMapper.selectList(
                    Wrappers.<StaJxFee>lambdaQuery()
                            .in(chapterIds.size() > 0, StaJxFee::getChapterId, chapterIds)
                            .eq(StaJxFee::getVersionId, versionId)
                            .orderBy(true, true, StaJxFee::getCode)
                            .orderBy(true, true, StaJxFee::getOrderNum)
            );
            //获取所有费用项编码
            for (StaJxFee stajxFee : staFbFees) {
                codesMap.put(stajxFee.getCode(), "1" + "@null" + "1");
            }
        } else if (CostDataConstanta.Tabs.JJ_3.getCode().equals(type)) {

        }
        Set<String> codes = codesMap.keySet();
        PageUtils.startPage();
        List<EvaluationDataPrice> list = evaluationDataPriceMapper.selectEvaluationDataPriceList(new EvaluationDataPrice() {{
            setCode(costDataEvaluteBo.getFyxCode());
            setName(costDataEvaluteBo.getFyxName());
            setPid(costDataEvaluteBo.getId());
        }});
        for (EvaluationDataPrice dataPrice : list) {
            if (CollUtil.isNotEmpty(codes) && !codes.contains(dataPrice.getCode())) continue;
            EvaluationDataPriceBo bo = new EvaluationDataPriceBo();
            BeanUtil.copyProperties(dataPrice,bo);
            BigDecimal modalNums = bo.getNumber();
            BigDecimal avgValue = bo.getSsavg();
            BigDecimal jqAvg = null;
            if (costDataEvaluteBo.getJqAvg()!=null){
                StringBuilder idAndAddress = new StringBuilder().append(bo.getOid()).append("=").append(bo.getRegion());
                jqAvg = getJqAvg2(idAndAddress.toString(),"view",costDataEvaluteBo);
                bo.setAvg(jqAvg);
            }else {
                jqAvg = bo.getAvg();
            }
            BigDecimal median = bo.getMedian();
            BigDecimal qdqxAvg = bo.getQdqxAvg();
            BigDecimal finalJqAvg = jqAvg;
            Map<BigDecimal,String> colorMap = new HashMap<BigDecimal,String>(){{
                put(modalNums,"2");
                put(avgValue,"2");
                put(finalJqAvg,"2");
                put(median,"2");
                put(qdqxAvg,"2");
            }};
            List<BigDecimal> sortValue = colorMap.keySet().stream().filter(v->v!=null).sorted().collect(Collectors.toList());//进行排序
            if (CollUtil.isNotEmpty(sortValue)){
                BigDecimal minValue = sortValue.get(0);
                BigDecimal maxValue = sortValue.get(sortValue.size() - 1);
                colorMap.put(minValue,"0");
                colorMap.put(maxValue,"1");
            }
            bo.setNumberColor(colorMap.get(modalNums));
            bo.setSsavgColor(colorMap.get(avgValue));
            bo.setAvgColor(colorMap.get(finalJqAvg));
            bo.setMedianColor(colorMap.get(median));
            bo.setQdqxAvgColor(colorMap.get(qdqxAvg));
            res.add(bo);
        }
        return res;
    }

    @Override
    public List<String> evaluteDataInfoIdList(CostDataEvaluteBo costDataEvaluteBo) {
        List<CostDataEvaluteBo> boList = evaluationCbInfoMapper.initTableDetailInfoData(new CostDataEvaluteBo() {{
            setPid(costDataEvaluteBo.getId());
        }});
        return boList.stream().map(CostDataEvaluteBo::getId).collect(Collectors.toList());
    }

    @Override
    public int updateEvaluationPrice(CostDataEvaluteBo costDataEvaluteBo) {
        int i;
        String resultId = costDataEvaluteBo.getId();
        String titleName = costDataEvaluteBo.getName();
        List<EvaluationDataPrice> priceSaveData = costDataEvaluteBo.getPriceSaveData();
        List<String> ids = costDataEvaluteBo.getIds();//明细id
        Map<BigDecimal, List<EvaluationDataPrice>> btjgsl = priceSaveData.stream().filter(v -> v.getUserPrice() != null).collect(Collectors.groupingBy(EvaluationDataPrice::getUserPrice, Collectors.toList()));
        //修改结果表
        EvaluationResults results = evaluationResultsMapper.selectEvaluationResultsById(resultId);
        results.setPjjgsj(titleName);
        results.setBtjgsl(btjgsl.size());
        results.setCount(priceSaveData.size());
        i = evaluationResultsMapper.updateById(results);
        //删除未选中的数据
        List<EvaluationDataPrice> dataPriceList = evaluationDataPriceMapper.selectEvaluationDataPriceList(new EvaluationDataPrice() {{
            setPid(resultId);
        }});
        List<String> dataPriceSrIds = priceSaveData.stream().map(EvaluationDataPrice::getId).collect(Collectors.toList());
        List<String> deleteDataIds = dataPriceList.stream().filter(v -> !dataPriceSrIds.contains(v.getId())).map(EvaluationDataPrice::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(deleteDataIds)){
            i = evaluationDataPriceMapper.deleteBatchIds(deleteDataIds);
        }
        //修改 数据明细
        for (EvaluationDataPrice saveDatum : priceSaveData) {
            EvaluationDataPrice dataPrice = evaluationDataPriceMapper.selectEvaluationDataPriceById(saveDatum.getId());
            dataPrice.setJgsl(saveDatum.getJgsl());
            dataPrice.setNumber(saveDatum.getNumber());
            dataPrice.setSsavg(saveDatum.getSsavg());
            dataPrice.setAvg(saveDatum.getAvg());
            dataPrice.setAvgType(costDataEvaluteBo.getJqAvg());
            dataPrice.setMedian(saveDatum.getMedian());
            dataPrice.setQdqxAvg(saveDatum.getQdqxAvg());
            dataPrice.setUserPrice(saveDatum.getUserPrice());
            dataPrice.setPriceRange(saveDatum.getPriceRange());
            dataPrice.setEvaluationDate(new Date());
            i = evaluationDataPriceMapper.updateById(dataPrice);
            if (CollUtil.isNotEmpty(ids)){
                List<EvaluationCbInfo> evaluationCbInfos = evaluationCbInfoMapper.selectEvaluationCbInfoList(new EvaluationCbInfo() {{
                    setPid(saveDatum.getId());
                }});
                List<String> infoIds = evaluationCbInfos.stream().filter(v->!ids.contains(v.getOid())).map(EvaluationCbInfo::getId).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(infoIds)){
                    i = evaluationCbInfoMapper.deleteBatchIds(infoIds);
                }
            }
        }
        return i;
    }

    @Override
    public List<EvaluationResults> findAllPjjg(CostDataEvaluteBo costDataEvaluteBo) {
        return evaluationResultsMapper.selectList(Wrappers.<EvaluationResults>lambdaQuery().eq(EvaluationResults::getIsassets, "1"));
    }

    /**
     * 众数
     * @param list
     * @return
     */
    public static BigDecimal getModalNums(List<BigDecimal> list) {
        Map<BigDecimal, Integer> map = new HashMap<>();
        if (list == null || list.size() == 0) {
            return null;
        }
        for (BigDecimal num : list) {
            Integer count = map.get(num);
            map.put(num,(count == null) ? 1 : count + 1);
        }
        Object[] objects = map.values().toArray();
        Arrays.sort(objects);
        Object object = objects[map.size() - 1];//值最大
        BigDecimal number = null;
        Set<BigDecimal> keys = map.keySet();
        for (BigDecimal key : keys) {
            Integer integer = map.get(key);
            if (integer.equals(object)){
                number = key;
            }
        }
        return number.setScale(3,BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 加权平均值
     * @param boList
     * @param option 下拉框选项
     * @return
     */
    public BigDecimal getJqAvg(List<CostDataEvaluteBo> boList,String option) {
        BigDecimal avg = null;
        Map<BigDecimal, List<CostDataEvaluteBo>> listMap = boList.stream().filter(v -> v.getPrice() != null).collect(Collectors.groupingBy(CostDataEvaluteBo::getPrice, Collectors.toList()));
        if (CollUtil.isNotEmpty(listMap)){
            Integer jgcsQS = 0; //'价格次数'权数之和
            double gclQS = 0;  //'工程量'权数之和
            double jgcsTotal = 0; // 兼 '成本合价'权数之和
            double gclTotal = 0;
            double cbhjTotal = 0;
            Set<BigDecimal> key = listMap.keySet();
            for (BigDecimal price : key) {
                BigDecimal unitPrice = price;//价格
                int jgcs = listMap.get(price).size();//价格次数
                if(StringUtil.isNotNullOrEmpty(option) && option.equals("2")){
                    List<String> dataJson = listMap.get(price).stream().filter(v->v.getDataJson()!=null).map(CostDataEvaluteBo::getDataJson).collect(Collectors.toList());
                    BigDecimal gcl = getGcl(dataJson);//该工程量指：同一价格的不同工程量之和
                    if (gcl != null) gclQS += gcl.doubleValue();
                    if (gcl != null && unitPrice != null) gclTotal += unitPrice.multiply(gcl).doubleValue();
                }
                jgcsQS += jgcs;
                jgcsTotal += unitPrice.multiply(new BigDecimal(jgcs)).doubleValue(); // 不同价格 x 次数
                cbhjTotal += unitPrice.multiply(unitPrice.multiply(new BigDecimal(jgcs))).doubleValue(); // 不同价格 x 成本合价
            }
            if (StringUtil.isNullOrEmpty(option) || option.equals("0") || option.equals("1")){
                //以出现次数为权数
                if (jgcsTotal == 0 || jgcsQS == 0) return new BigDecimal("0.000");
                avg = new BigDecimal(jgcsTotal).divide(new BigDecimal(jgcsQS),3,BigDecimal.ROUND_HALF_UP);
            }else if (option.equals("2")){
                //以工程量为权数
                if (gclTotal == 0 || gclQS == 0) return new BigDecimal("0.000");
                avg = new BigDecimal(gclTotal).divide(new BigDecimal(gclQS),3,BigDecimal.ROUND_HALF_UP);
            }else if (option.equals("3")){
                //以合价为权数
                if (cbhjTotal == 0 || jgcsTotal == 0) return new BigDecimal("0.000");
                avg = new BigDecimal(cbhjTotal).divide(new BigDecimal(jgcsTotal),3,BigDecimal.ROUND_HALF_UP);
            }
        }
        return avg;
    }

    /**
     * 加权平均值
     * @param id id+address
     * @param viewOrEdit
     * @param bo
     * @return
     */
    public BigDecimal getJqAvg2(String id,String viewOrEdit,CostDataEvaluteBo bo) {
        //获取该条数据的id 根据id获取对应price和count（price）
        if (StringUtil.isNullOrEmpty(id)) return null;
        String option = bo.getJqAvg();//下拉框选项
        BigDecimal avg = null;
        List<String> idAndAddress = Arrays.asList(id.split("=", -1));
        if (CollUtil.isEmpty(idAndAddress)) return null;
        String sreachId = idAndAddress.get(0);
        if(viewOrEdit != null && viewOrEdit.equals("view")){
            EvaluationDataPrice dataPrice = evaluationDataPriceMapper.selectEvaluationDataPriceById(idAndAddress.get(0));
            if (dataPrice != null) sreachId = dataPrice.getOid();
        }
        String finalSreachId = sreachId;
        List<CostDataEvaluteBo> boList = evaluationResultsMapper.selectCleanDataEvaluteList(new CostDataEvaluteBo() {{
            setId(finalSreachId);
            setAddress(idAndAddress.get(1));
            setPriceType(bo.getPriceType());
            setProjectDept(bo.getProjectDept());
            setOids(bo.getList());
        }});
        Map<BigDecimal, List<CostDataEvaluteBo>> listMap = boList.stream().filter(v -> v.getPrice() != null).collect(Collectors.groupingBy(CostDataEvaluteBo::getPrice, Collectors.toList()));
        if (CollUtil.isNotEmpty(listMap)){
            Integer jgcsQS = 0; //'价格次数'权数之和
            double gclQS = 0;  //'工程量'权数之和
            double jgcsTotal = 0; // 兼 '成本合价'权数之和
            double gclTotal = 0;
            double cbhjTotal = 0;
            Set<BigDecimal> key = listMap.keySet();
            for (BigDecimal price : key) {
                BigDecimal unitPrice = price;//价格
                int jgcs = listMap.get(price).size();//价格次数
                if(StringUtil.isNotNullOrEmpty(option) && option.equals("2")){
                    List<String> dataJsonList = listMap.get(price).stream().filter(v -> v.getDataJson() != null).map(CostDataEvaluteBo::getDataJson).collect(Collectors.toList());
                    BigDecimal gcl = getGcl(dataJsonList);//该工程量指：同一价格的不同工程量之和
                    if (gcl != null) gclQS += gcl.doubleValue();
                    if (gcl != null && unitPrice != null) gclTotal += unitPrice.multiply(gcl).doubleValue();
                }
                jgcsQS += jgcs;
                jgcsTotal += unitPrice.multiply(new BigDecimal(jgcs)).doubleValue(); // 不同价格 x 次数
                cbhjTotal += unitPrice.multiply(unitPrice.multiply(new BigDecimal(jgcs))).doubleValue(); // 不同价格 x 成本合价
            }
            if (StringUtil.isNullOrEmpty(option) || option.equals("0") || option.equals("1")){
                //以出现次数为权数
                if (jgcsTotal == 0 || jgcsQS == 0) return new BigDecimal("0.000");
                avg = new BigDecimal(jgcsTotal).divide(new BigDecimal(jgcsQS),3,BigDecimal.ROUND_HALF_UP);
            }else if (option.equals("2")){
                //以工程量为权数
                if (gclTotal == 0 || gclQS == 0) return new BigDecimal("0.000");
                avg = new BigDecimal(gclTotal).divide(new BigDecimal(gclQS),3,BigDecimal.ROUND_HALF_UP);
            }else if (option.equals("3")){
                //以合价为权数
                if (cbhjTotal == 0 || jgcsTotal == 0) return new BigDecimal("0.000");
                avg = new BigDecimal(cbhjTotal).divide(new BigDecimal(jgcsTotal),3,BigDecimal.ROUND_HALF_UP);
            }
        }
        return avg;
    }

    /**
     * 工程量
     * @param linkDataJsonList
     * @return
     */
    public BigDecimal getGcl(List<String> linkDataJsonList) {
        BigDecimal gcl = null;
        if (CollUtil.isEmpty(linkDataJsonList)) return gcl;
        if (CollUtil.isNotEmpty(linkDataJsonList)){
            List<EcoCbfeeitem> cbFeeItemList = new ArrayList<>();
            for (String data : linkDataJsonList) {
                EcoCbfeeitem cbFeeItem = JSON.parseObject(data, EcoCbfeeitem.class);
                cbFeeItemList.add(cbFeeItem);
            }
            if (CollUtil.isNotEmpty(cbFeeItemList)){
                gcl = cbFeeItemList.stream().filter(v -> v.getTargetamout() != null).map(EcoCbfeeitem::getTargetamout).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
        }
        return gcl;
    }

    /**
     * 中位数
     * @param list
     * @return
     */
    public static BigDecimal getMedian(List<BigDecimal> list) {
        if (list == null || list.size() == 0) {
            return null;
        }
        List<BigDecimal> sortPrice = list.stream().sorted().collect(Collectors.toList());//对 价格 进行排序
        int i = sortPrice.size() / 2;
        return sortPrice.size()%2 == 0 ? (sortPrice.get(i - 1).add(sortPrice.get(i))).divide(new BigDecimal(2)).setScale(3,BigDecimal.ROUND_HALF_UP) : sortPrice.get(i).setScale(3,BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 去大去小平均值
     * @param list
     * @return
     */
    public static BigDecimal getQdqxAvg(List<BigDecimal> list) {
        if (list == null || list.size() == 0) {
            return null;
        }
        BigDecimal avgValue = null;
        List<BigDecimal> sortPrice = list.stream().sorted().collect(Collectors.toList());//对 价格 进行排序
        if (CollUtil.isNotEmpty(sortPrice)){
            double min = sortPrice.get(0).multiply(new BigDecimal(0.95)).doubleValue();//最小值去除5%
            double max = sortPrice.get(sortPrice.size() - 1).multiply(new BigDecimal(0.95)).doubleValue();//最大值去除5%
            sortPrice.set(0,new BigDecimal(min));
            sortPrice.set(sortPrice.size() - 1,new BigDecimal(max));
            avgValue = sortPrice.stream().reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(sortPrice.size()), 3, BigDecimal.ROUND_HALF_UP);
        }
        return avgValue;
    }
}
